﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using LiuYan.Base;
using LiuYan.Base;
using LiuYan.Entity;
using LiuYan.Service;

namespace LiuYan.Web.Areas.Admin.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Admin/Login/

        public ActionResult Index(string id)
        {
            ViewData["t"] = id;
            return View();
        }
        /// <summary>
        /// 获取登陆验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult ValideteImg()
        {
            VerificationCode verificationCode = new VerificationCode();
            string rnd = string.Empty; //验证码
            Bitmap map = verificationCode.DrawImage(out rnd);
            Response.Cookies.Add(new HttpCookie("CheckCode", rnd)); //将验证码放入cookie
            MemoryStream ms = new MemoryStream();
            map.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return File(ms.ToArray(), "image/gif");
        }
        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        ///  /// <param name="yzm">验证码</param>
        /// <returns></returns>
        public string UserLogin(string username, string pwd, string yzm)
        {
            //try
            //{
                string checkCode = Request.Cookies["CheckCode"].Value; //获取验证码
                Response.Cookies["CheckCode"].Expires = DateTime.Now; //设置cookie过期时间
                string s = checkCode.ToUpper();
                if (checkCode.ToLower() != yzm.ToLower() || checkCode.ToUpper() != yzm.ToUpper())
                {
                    return "errorcode";
                }
                DataTable table = new LoginService().Login(username, pwd);
                if (table.Rows.Count != 0)
                {
                    if (Convert.ToInt32(table.Rows[0]["IsExit"]) == 1)//账号被禁用
                    {
                        return "-1";
                    }
                   
                    TB_Admin entity = DataConvert.ConvertToEntity<TB_Admin>(table.Rows[0]);
                    entity.PassWord = null;
                    entity.Name = Server.UrlEncode(entity.Name);
                    Response.Cookies.Add(new HttpCookie("user",JsonConvert.SerializeObject(entity))); 
                    Session["user"] = entity;
                    //Session.Timeout = 240;
                }
                else
                {
                    return "0";
                }
                return "1";

            //}
            //catch (Exception e)
            //{

            //}
            return "";
        }

     
    }
}
